using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MaterialFlipperPlusSounds : KnowsWhenSeen
{
	public FlickerMaterialSoundStep[] m_FlickerMatSteps;
	public int m_EffectsWhichMatSlot = 0;

	private int m_currStepIdx = -1;
	private int m_matId;
	public float m_currCountdown = 0.01f;

	void Start()
	{
		Start_For_KnowsWhenSeen();
	}

	override public void Saw()
	{
	}
	
	override public void LookedAway()
	{
		if ( m_ResetOnLookAway && m_PauseTilSeen )
		{
			m_currStepIdx = -1;
			GotoNextStep();
		}
	}
	
	void Update() 
	{
		Update_For_KnowsWhenSeen();

		if (   m_PauseTilSeen   &&   ( ! CanIBeSeen() )   )
		{
			return; // We care that we are seen and are not seen, so exit Update here
		}
		else
		{
			if ( m_currCountdown > 0 )
			{
				m_currCountdown -= Time.deltaTime;
				if ( m_currCountdown <= 0f )
				{
					GotoNextStep();
				}
			}
		}
	}

	void GotoNextStep()
	{
		if ( m_FlickerMatSteps.Length > 0 )
		{
			m_currStepIdx++;
			if ( m_currStepIdx > m_FlickerMatSteps.Length - 1 )
			{
				bool pausedButSeen = ( m_PauseTilSeen && CanIBeSeen() );
				if ( m_Loop && ( (!m_PauseTilSeen) || (pausedButSeen) )  ) // looping and not paused by seen-ness or pausedButSeen
				{
					m_currStepIdx = 0;
				}
				else
				{
					m_currStepIdx = m_FlickerMatSteps.Length; // Keep index past the end of the array and...

					return; // Prevents you from looping while seen

				}
			}
			
			SetMat( m_FlickerMatSteps[ m_currStepIdx ].m_Mat );
			AudioClip ac = m_FlickerMatSteps[ m_currStepIdx ].m_AudioClip;
			if ( ac != null ) 
			{
				PlaySound( ac );
			}
			
			m_currCountdown = m_FlickerMatSteps[ m_currStepIdx ].m_Seconds;
		}
	}

	void PlaySound( AudioClip ac )
	{
		if ( audio == null )
		{
			AudioSource.PlayClipAtPoint( ac, Camera.main.transform.position );
		}
		else
		{
			audio.PlayOneShot( ac );
		}
	}

	void SetMat( Material matToSet )
	{
		if ( renderer != null )
		{
			if ( renderer.materials != null )
			{
				if ( m_EffectsWhichMatSlot < renderer.materials.Length ) // not past end
				{
					// Make a copy of mat array
					Material[] copysMats = new Material[renderer.materials.Length];
					for(int i=0; i<copysMats.Length;i++)
					{
						if ( i == m_EffectsWhichMatSlot )
						{
							copysMats[i] = matToSet; // <<<<<<<<<<<< Finally, we get to set it !!!!
						}
						else // just copy the one that was there
						{
							copysMats[i] = renderer.materials[i];
						}
					}
					renderer.materials = copysMats;
				}
			}
		}
	}

}

[System.Serializable]
public class FlickerMaterialSoundStep
{
	public Material m_Mat;
	public float m_Seconds = 0.5f;
	public AudioClip m_AudioClip;
}